#!/usr/bin/env python3
"""
同步服务
负责定时从Shopify同步数据到系统
"""

import asyncio
import logging
from datetime import datetime
from sqlalchemy.ext.asyncio import AsyncSession
from sqlmodel import select
from database.connection import async_session
from database.models import Product, Order, ShopifySyncLog, ShopifyResourceType
from services.shopify_service import shopify_service
import json

logger = logging.getLogger(__name__)


class SyncService:
    """同步服务类"""
    
    def __init__(self):
        self.enabled = True
        self.running = False
        self.sync_interval = 3600  # 默认1小时同步一次
    
    async def start_scheduled_sync(self):
        """启动定时同步任务"""
        if not self.enabled or self.running:
            return
        
        self.running = True
        logger.info("定时同步任务已启动")
        
        try:
            while self.running:
                # 执行同步任务
                await self.sync_all_data()
                
                # 等待下一次同步
                for _ in range(self.sync_interval):
                    if not self.running:
                        break
                    await asyncio.sleep(1)
        
        except Exception as e:
            logger.error(f"定时同步任务异常: {e}")
        finally:
            self.running = False
            logger.info("定时同步任务已停止")
    
    async def stop_scheduled_sync(self):
        """停止定时同步任务"""
        self.running = False
        logger.info("定时同步任务正在停止...")
    
    async def sync_all_data(self):
        """同步所有数据"""
        logger.info("开始执行全量数据同步")
        
        # 同步商品数据
        await self.sync_products()
        
        # 同步订单数据
        await self.sync_orders()
        
        logger.info("全量数据同步完成")
    
    async def sync_products(self):
        """同步商品数据"""
        session = None
        try:
            session = await async_session()
            logger.info("开始同步Shopify商品数据")
            
            # 调用Shopify服务获取商品数据
            shopify_products = await shopify_service.sync_products_from_shopify()
            logger.info(f"接收到 {len(shopify_products)} 个商品数据")
                
            new_count = 0
            updated_count = 0
            failed_count = 0
            
            if not shopify_products:
                logger.warning("未获取到任何商品数据")
                return
            
            for shopify_product in shopify_products:
                try:
                    # 查找是否已存在对应商品
                    result = await session.execute(
                        select(Product).where(Product.shopify_product_id == str(shopify_product['id']))
                    )
                    existing_product = result.scalar_one_or_none()
                    
                    if not existing_product:
                        # 创建新商品
                        new_product = Product(
                            name=shopify_product.get('title', '未知商品'),
                            description=shopify_product.get('body_html', ''),
                            price=float(shopify_product.get('price', '0.00')),
                            category_id=1,
                            stock_quantity=0,
                            is_active=shopify_product.get('status') == 'active',
                            shopify_product_id=str(shopify_product['id']),
                            created_at=datetime.utcnow(),
                            updated_at=datetime.utcnow()
                        )
                        
                        # 处理变体信息
                        if 'variants' in shopify_product and shopify_product['variants']:
                            first_variant = shopify_product['variants'][0]
                            new_product.shopify_variant_id = str(first_variant.get('id', ''))
                            new_product.price = float(first_variant.get('price', '0.00'))
                            new_product.stock_quantity = first_variant.get('inventory_quantity', 0)
                        
                        session.add(new_product)
                        await session.commit()
                        new_count += 1
                    else:
                        # 更新现有商品
                        existing_product.name = shopify_product.get('title', existing_product.name)
                        existing_product.description = shopify_product.get('body_html', existing_product.description)
                        existing_product.is_active = shopify_product.get('status') == 'active'
                        existing_product.updated_at = datetime.utcnow()
                        
                        # 更新变体信息
                        if 'variants' in shopify_product and shopify_product['variants']:
                            first_variant = shopify_product['variants'][0]
                            existing_product.price = float(first_variant.get('price', str(existing_product.price)))
                            existing_product.stock_quantity = first_variant.get('inventory_quantity', existing_product.stock_quantity)
                        
                        await session.commit()
                        updated_count += 1
                    
                except Exception as e:
                    logger.error(f"同步单个商品失败: {e}")
                    failed_count += 1
                    await session.rollback()
            
            logger.info(f"商品同步完成: 新增 {new_count}, 更新 {updated_count}, 失败 {failed_count}")
            
        except Exception as e:
            logger.error(f"商品同步异常: {e}")
            if session:
                await session.rollback()
        finally:
            if session:
                await session.close()
    
    async def sync_orders(self):
        """同步订单数据"""
        session = None
        try:
            session = await async_session()
            # 记录开始同步时间
            start_time = datetime.utcnow()
            logger.info("开始同步Shopify订单数据")
            logger.info("订单同步功能已启用")
            
            # 调用Shopify服务获取订单数据
            shopify_orders = await shopify_service.sync_from_shopify()
            logger.info(f"接收到 {len(shopify_orders)} 个订单数据")
                
            new_count = 0
            updated_count = 0
            skipped_count = 0
            failed_count = 0
                
            if not shopify_orders:
                logger.warning("未获取到任何订单数据")
                return
            
            for shopify_order in shopify_orders:
                try:
                    # 查找是否已存在对应订单
                    result = await session.execute(
                        select(Order).where(Order.shopify_order_id == str(shopify_order['id']))
                    )
                    existing_order = result.scalar_one_or_none()
                    
                    # 转换Shopify订单状态到系统状态
                    status_map = {
                        'fulfilled': 'delivered',
                        'partial': 'shipped',
                        'cancelled': 'cancelled',
                        'unfulfilled': 'processing'
                    }
                    
                    # 获取订单项信息
                    line_items = shopify_order.get('line_items', [])
                    if not line_items:
                        logger.warning(f"跳过没有订单项的Shopify订单: {shopify_order.get('id')}")
                        skipped_count += 1
                        continue
                    
                    # 获取第一个订单项作为主要商品信息
                    line_item = line_items[0]
                    
                    if not existing_order:
                        # 创建新订单
                        logger.info(f"创建新订单: {shopify_order.get('name')}")
                        
                        # 先确保有一个产品存在（如果没有，创建一个基础产品）
                        product_result = await session.execute(select(Product).limit(1))
                        products = product_result.scalars().all()
                        
                        if not products:
                            logger.info("没有找到产品，创建一个默认产品")
                            default_product = Product(
                                name="默认产品",
                                description="这是一个用于测试的默认产品",
                                price=99.99,
                                category_id=1,  # 设置默认分类ID为1
                                stock_quantity=100,
                                is_active=True
                            )
                            session.add(default_product)
                            await session.commit()
                            product_id = default_product.id
                        else:
                            product_id = products[0].id
                        
                        # 设置默认用户ID为1（假设系统中有默认管理员）
                        user_id = 1
                        
                        customer = shopify_order.get('customer', {})
                        
                        new_order = Order(
                            user_id=user_id,
                            product_id=product_id,
                            model_3d_id=1,  # 设置默认的3D模型ID
                            quantity=line_item.get('quantity', 1),
                            unit_price=float(line_item.get('price', '0.00')),
                            total_amount=float(shopify_order.get('total_price', '0.00')),
                            status=status_map.get(shopify_order.get('fulfillment_status'), 'processing'),
                            payment_status=shopify_order.get('financial_status', 'unpaid'),
                            order_number=shopify_order.get('name', ''),
                            shopify_order_id=str(shopify_order['id']),
                            shipping_address=str(shopify_order.get('shipping_address', {})),
                            shipping_name=f"{customer.get('first_name', '')} {customer.get('last_name', '')}".strip() or "默认收货人",
                            shipping_phone="13800138000",  # 设置默认手机号
                            customer_name=f"{customer.get('first_name', '')} {customer.get('last_name', '')}".strip(),
                            customer_email=customer.get('email', ''),
                            created_at=datetime.utcnow()
                        )
                        
                        session.add(new_order)
                        await session.flush()  # 先flush获取ID
                        await session.commit()
                        new_count += 1
                        logger.info(f"成功创建订单: {new_order.order_number} (ID: {new_order.id})")
                        
                        # 记录同步日志
                        sync_log = ShopifySyncLog(
                            order_id=new_order.id,
                            shopify_resource_id=str(shopify_order['id']),
                            shopify_resource_type=ShopifyResourceType.ORDER,
                            shopify_operation='create',
                            request_data=str(shopify_order),
                            response_data=f"{{\"id\": {new_order.id}}}",
                            sync_status='success',
                            response_time=round((datetime.utcnow() - start_time).total_seconds() * 1000),
                            synced_at=datetime.utcnow(),
                            created_at=datetime.utcnow()
                        )
                        session.add(sync_log)
                        await session.commit()
                    else:
                        # 更新现有订单
                        logger.info(f"更新现有订单: {existing_order.order_number}")
                        existing_order.total_amount = float(shopify_order.get('total_price', str(existing_order.total_amount)))
                        existing_order.status = status_map.get(shopify_order.get('fulfillment_status'), existing_order.status)
                        existing_order.payment_status = shopify_order.get('financial_status', existing_order.payment_status)
                        
                        # 更新物流信息（如果有）
                        if 'fulfillments' in shopify_order:
                            for fulfillment in shopify_order['fulfillments']:
                                if fulfillment.get('tracking_number'):
                                    existing_order.tracking_number = fulfillment['tracking_number']
                                    existing_order.shipping_company = fulfillment.get('tracking_company', '')
                                    break
                        
                        await session.commit()
                        updated_count += 1
                        
                        # 记录同步日志
                        sync_log = ShopifySyncLog(
                            order_id=existing_order.id,
                            shopify_resource_id=str(shopify_order['id']),
                            shopify_resource_type=ShopifyResourceType.ORDER,
                            shopify_operation='update',
                            request_data=str(shopify_order),
                            response_data=f"{{\"id\": {existing_order.id}}}",
                            sync_status='success',
                            response_time=round((datetime.utcnow() - start_time).total_seconds() * 1000),
                            synced_at=datetime.utcnow(),
                            created_at=datetime.utcnow()
                        )
                        session.add(sync_log)
                        await session.commit()
                    
                except Exception as e:
                    logger.error(f"同步单个订单失败: {e}")
                    failed_count += 1
                    await session.rollback()
                    
                    try:
                        # 记录失败日志
                        sync_log = ShopifySyncLog(
                            shopify_resource_id=str(shopify_order.get('id', 'unknown')),
                            shopify_resource_type=ShopifyResourceType.ORDER,
                            shopify_operation='sync',
                            request_data=str(shopify_order),
                            sync_status='failed',
                            error_message=str(e),
                            response_time=round((datetime.utcnow() - start_time).total_seconds() * 1000),
                            created_at=datetime.utcnow()
                        )
                        session.add(sync_log)
                        await session.commit()
                    except Exception as log_error:
                        logger.error(f"记录失败日志也失败了: {log_error}")
            
            logger.info(f"订单同步完成: 新增 {new_count}, 更新 {updated_count}, 跳过 {skipped_count}, 失败 {failed_count}")
                
        except Exception as e:
            logger.error(f"订单同步异常: {e}")
            if session:
                await session.rollback()
        finally:
            if session:
                await session.close()


# 创建全局同步服务实例
sync_service = SyncService()
